package com.ys.service.Impl;

import com.ys.mapper.MenuMapper;
import com.ys.mapper.RelationshipMapper;
import com.ys.pojo.Menu;
import com.ys.service.MenuService;
import com.ys.vo.TreeVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("menuService")
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findByAdminAndPwd(String name, String pwd) {
        return menuMapper.findByAdminAndPwd(name,pwd);
    }

    @Override
    public List<Menu> findByAdminAndPwds(String name, String pwd,int id) {
        return menuMapper.findByAdminAndPwds(name,pwd,id);
    }

    @Override
    public List<String> finByGrname(String userCode) {
        return menuMapper.finByGrname(userCode);
    }


    @Override
    public List<TreeVo> finByShouquan(Integer id) {
        List<TreeVo> treeVo = new ArrayList<>();
        List<Menu> list1 = menuMapper.finByShouquan(0);
        list1.forEach(x1->{
            TreeVo vo1 = this.transfer(x1,id);
            treeVo.add(vo1);
            List<Menu> list2 = menuMapper.finByShouquan(x1.getId());
            list2.forEach(x2->{
                TreeVo vo2= this.transfer(x2,id);
                vo1.getChildren().add(vo2);
                List<Menu> list3 = menuMapper.finByShouquan(x2.getId());
                    list3.forEach(x3->{
                        TreeVo vo3=this.transfer(x3,id);
                        vo2.getChildren().add(vo3);
                    });
            });
        });
        return treeVo;
    }

    @Resource
    private RelationshipMapper relationshipMapper;

    private TreeVo transfer(Menu m,Integer roleId){
        List<Integer> list = relationshipMapper.select(roleId);//查询出当前用户的所有权限
        TreeVo vo=new TreeVo();
        vo.setTitle(m.getGname());
        vo.setExpand(false);
        vo.setId(m.getAdfunction());
        int count=menuMapper.count(m.getId());
        if(list.contains(m.getAdfunction())&&count==0) {    //如果为0,说明为叶子节点
            vo.setChecked(true);
        }
        if("menu".equals(m.getGnameType())){
            List<TreeVo> children=new ArrayList<>();
            vo.setChildren(children);
        }
        return  vo;
    }

}
